

var formatDoc = function (doc) {
    var data = doc.toJSON({ getters: true });
    data.id = doc._id.toString();
    // data.createdAt = doc.createdAt.getTime();
    // data.updatedAt = doc.updatedAt.getTime();

    if (!data.hasOwnProperty('code')) {
        data.code = '';
    };
    if (!data.hasOwnProperty('formData')) {
        data.formData = '';
    };
    if (!data.hasOwnProperty('requestType')) {
        data.requestType = 'json';
    };
    delete data.createdAt;
    delete data.updatedAt;
    delete data.disable;
    delete data._id;
    return data;
};
// 格式化多行数据
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};

var api = function (mongoose, Schema, PorjectName) {

    const contentSchema = new Schema({
        title: { type: String, required: true },
        requestURL: { type: String },
        header: { type: String },
        requestData: { type: String },
        contentType: { type: String, enum: ['POST', 'GET', 'PUT', 'DEL', 'folder'], required: true },
        contentIndex: { type: Number, min: 1, default: 1 },
        parentId: { type: String, default: null },
        description: String,
        disable: { type: Boolean, default: false },
        code: { type: String },
        formData: { type: String },
        requestType: { type: String, enum: ['json', 'form'] },
    }, { timestamps: true });

    this.module = mongoose.model(PorjectName, contentSchema, PorjectName);

};
api.prototype.creat = function (doc, cb) {
    var data = new this.module(doc);
    // 将单行数据插入到数据库
    data.save(function (err, doc) {
        if (err) {
            cb(err.message, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};
api.prototype.getAll = function (cb) {
    this.module.find({ disable: false }, function (err, docs) {
        if (err) {
            cb(err.message, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};
api.prototype.upData = function (id, _doc, cb) {
    // 更新数据库单条记录
    this.module.findById(id, function (err, doc) {
        doc.title = _doc.title;
        doc.requestURL = _doc.requestURL;
        doc.requestData = _doc.requestData;
        doc.contentType = _doc.contentType;
        doc.header = _doc.header;
        doc.contentIndex = _doc.contentIndex;
        doc.parentId = _doc.parentId;
        doc.description = _doc.description;
        doc.disable = false;
        doc.code = _doc.code;
        doc.formData = _doc.formData;
        doc.requestType = _doc.requestType;
        // 储存数据
        doc.save(function (err, doc) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDoc(doc));
            };
        })
    });
};
api.prototype.delete = function (id, cb) {
    // 删除单条记录
    this.module.findById(id, (err, doc) => {
        var docId = doc._id.toString();
        var _parentId = doc.parentId;
        doc.disable = true;
        // 保存更改
        doc.save((err, doc) => {
            if (err) {
                cb(err.message, null);
            } else {
                // 当删除的文件为文件夹时
                if (doc.contentType == 'folder') {
                    this.module.update({ parentId: docId }, { parentId: _parentId }, { multi: true }, function (err, docs) {
                        if (err) {
                            cb(err.message, null);
                        } else {
                            cb(false, null);
                        };
                    });
                } else {
                    cb(false, null);
                };
            };
        });
    });
};
api.prototype.search = function (name, type, cb) {
    var query = {}
    if (type != 'ALL') {
        query.contentType = type;
    } else {
        query.contentType = { $ne: 'folder' };
    };
    name = name.replace(/\*/g, '\\*');
    name = name.replace(/\//g, '\\/');
    name = name.replace(/\?/g, '\\?');
    name = name.replace(/\&/g, '\\&');
    name = name.replace(/\%/g, '\\%');
    name = name.replace(/\=/g, '\\=');
    name = name.replace(/\+/g, '\\+');

    query.$or = [
        { requestURL: { $regex: new RegExp(name) } },
        { title: { $regex: new RegExp(name) } }
    ]

    query.disable = false;
    if (name.toString().length > 30) {
        cb('too lang', null);
    } else {
        this.module.find(query, function (err, docs) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDocs(docs));
            };
        });
    };
};
api.prototype.GetByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var _data = [];
    var _this = this;
    var index = 0
    var findById = function () {
        _this.module.findById(_array[index], function (err, doc) {
            if (err) {
                cb(err);
            } else {
                _data.push(doc);
                if (index >= _array.length - 1) {
                    cb(false, formatDocs(_data));
                } else {
                    findById(index++);
                };
            }
        });
    };
    findById();
};


module.exports = api;